package com.jlu.springbootjwt.controller;


import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureGenerationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.jlu.springbootjwt.entity.User;
import com.jlu.springbootjwt.service.UserService;
import com.jlu.springbootjwt.utils.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class TestContoller {


  @Autowired
  private UserService userService;

  @GetMapping("/test")
  public String test(){

    return "login ok!";
  }

  @GetMapping("/user/login")
  public Map<String,Object> login(User user){

    HashMap<String, Object> map = new HashMap<>();

    try {
      User userDB = userService.login(user);

      HashMap<String, String> payload = new HashMap<>();

      payload.put("name",userDB.getName());
      payload.put("id",String.valueOf(userDB.getId()));
      String token = JWTUtil.getToken(payload);

      map.put("state",true);
      map.put("msg","认证成功");
      map.put("token",token);//响应token
    }catch (Exception e){
      map.put("state",false);
      map.put("msg",e.getMessage());
    }
    return map;
  }

  @PostMapping("user/test")
  public Map<String,Object> verify(HttpServletRequest request){

    HashMap<String, Object> map = new HashMap<>();

    String token = request.getHeader("token");

    DecodedJWT verrify = JWTUtil.verrify(token);

    log.info("用户id：[{}]",verrify.getClaim("id").asString());
    log.info("用户名：[{}]",verrify.getClaim("name").asString());

    map.put("state:",true);
    map.put("msg:","验证成功");
    return map;
  }
}
